package com.lateam2010.register.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class Item extends Composite {

	private static ItemUiBinder uiBinder = GWT.create(ItemUiBinder.class);

	interface ItemUiBinder extends UiBinder<Widget, Item> {
	}

	interface Style extends CssResource {
		String deleted();
	}

	@UiField Style style;
	@UiField Label email;
	@UiField Label name;
	@UiField Button delete;
	
	private final RegisterServiceAsync service;
	private final TextBox password;
	private final Label error;

	public Item(TextBox password, Label error, RegisterServiceAsync service, String email, String name) {
		this.service = service;
		this.password = password;
		this.error = error;
		initWidget(uiBinder.createAndBindUi(this));
		this.email.setText(email);
		this.name.setText(name);
	}

	@UiHandler("delete")
	void onClick(ClickEvent e) {
		if (Window.confirm("Delete: " + email.getText() + "?")) {
			error.setVisible(false);
			delete.setVisible(false);
			service.delete(password.getText(), email.getText(), new AsyncCallback<Void>() {
				@Override
				public void onFailure(Throwable caught) {
					error.setVisible(true);
					delete.setVisible(true);
				}
				@Override
				public void onSuccess(Void result) {
					email.addStyleName(style.deleted());
					name.addStyleName(style.deleted());
				}
			});
		}
	}

}
